import React, { useState, useCallback } from 'react'
import { Upload, Button, message, Card, Spin, Alert } from 'antd'
import { UploadOutlined, EyeOutlined, DeleteOutlined } from '@ant-design/icons'
import apiService from '../services/api'

function ImageUploader() {
  const [uploadedFile, setUploadedFile] = useState(null)
  const [ocrResult, setOcrResult] = useState(null)
  const [isProcessing, setIsProcessing] = useState(false)
  const [previewVisible, setPreviewVisible] = useState(false)

  // 处理文件上传
  const handleUpload = useCallback(async (file) => {
    // 验证文件类型
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif']
    if (!allowedTypes.includes(file.type)) {
      message.error('只支持 JPG、PNG、GIF 格式的图片')
      return false
    }

    // 验证文件大小（最大 10MB）
    const maxSize = 10 * 1024 * 1024
    if (file.size > maxSize) {
      message.error('图片大小不能超过 10MB')
      return false
    }

    setUploadedFile(file)
    setIsProcessing(true)

    try {
      // 调用 OCR API
      const response = await apiService.uploadImageForOCR(file)

      if (response.success) {
        setOcrResult(response.data)
        message.success('OCR 识别完成')

        // 将 OCR 结果传递给父组件（通过全局状态或回调）
        if (window.onOCRResult) {
          window.onOCRResult(response.data)
        }
      } else {
        throw new Error(response.error || 'OCR 识别失败')
      }
    } catch (error) {
      console.error('OCR processing failed:', error)
      message.error(`OCR 识别失败: ${error.message}`)
      setOcrResult(null)
    } finally {
      setIsProcessing(false)
    }

    return false // 阻止默认上传行为
  }, [])

  // 删除上传的文件
  const handleRemove = useCallback(() => {
    setUploadedFile(null)
    setOcrResult(null)
    if (window.onOCRResult) {
      window.onOCRResult(null)
    }
  }, [])

  // 预览图片
  const handlePreview = useCallback(() => {
    setPreviewVisible(true)
  }, [])

  // 上传组件配置
  const uploadProps = {
    accept: 'image/*',
    showUploadList: false,
    beforeUpload: handleUpload,
    disabled: isProcessing
  }

  return (
    <div>
      <Card
        title="📸 图片上传 (OCR 识别)"
        size="small"
        style={{ marginBottom: 16 }}
      >
        {/* 上传区域 */}
        <Upload {...uploadProps}>
          <div
            style={{
              border: '2px dashed #d9d9d9',
              borderRadius: 8,
              padding: 20,
              textAlign: 'center',
              cursor: isProcessing ? 'not-allowed' : 'pointer',
              background: isProcessing ? '#f5f5f5' : '#fafafa',
              transition: 'all 0.3s'
            }}
          >
            {isProcessing ? (
              <div>
                <Spin size="large" />
                <div style={{ marginTop: 12, color: '#1890ff' }}>
                  正在识别图片内容...
                </div>
              </div>
            ) : (
              <div>
                <UploadOutlined style={{ fontSize: 24, color: '#1890ff' }} />
                <div style={{ marginTop: 8 }}>
                  点击或拖拽图片到此处上传
                </div>
                <div style={{ fontSize: 12, color: '#999', marginTop: 4 }}>
                  支持 JPG、PNG、GIF 格式，最大 10MB
                </div>
              </div>
            )}
          </div>
        </Upload>

        {/* 上传的文件预览 */}
        {uploadedFile && (
          <div style={{ marginTop: 16 }}>
            <Card size="small" style={{ background: '#f6ffed', border: '1px solid #b7eb8f' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <img
                  src={URL.createObjectURL(uploadedFile)}
                  alt="预览"
                  style={{
                    width: 60,
                    height: 60,
                    objectFit: 'cover',
                    borderRadius: 4,
                    border: '1px solid #d9d9d9'
                  }}
                />
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 500, marginBottom: 4 }}>
                    {uploadedFile.name}
                  </div>
                  <div style={{ fontSize: 12, color: '#666' }}>
                    {(uploadedFile.size / 1024).toFixed(1)} KB
                  </div>
                </div>
                <div style={{ display: 'flex', gap: 8 }}>
                  <Button
                    size="small"
                    icon={<EyeOutlined />}
                    onClick={handlePreview}
                  >
                    预览
                  </Button>
                  <Button
                    size="small"
                    danger
                    icon={<DeleteOutlined />}
                    onClick={handleRemove}
                  >
                    删除
                  </Button>
                </div>
              </div>
            </Card>
          </div>
        )}

        {/* OCR 结果展示 */}
        {ocrResult && (
          <div style={{ marginTop: 16 }}>
            <Alert
              message="🎯 OCR 识别结果"
              description={
                <div>
                  <p><strong>金额:</strong> ¥{ocrResult.amount}</p>
                  <p><strong>订单号:</strong> {ocrResult.order_id}</p>
                  <p><strong>日期:</strong> {ocrResult.date}</p>
                  {ocrResult.confidence && (
                    <p><strong>置信度:</strong> {(ocrResult.confidence * 100).toFixed(1)}%</p>
                  )}
                </div>
              }
              type="success"
              showIcon
            />

            {/* 识别的完整文本（如果有） */}
            {ocrResult.full_text && (
              <Card size="small" style={{ marginTop: 12 }}>
                <strong>识别的完整文本:</strong>
                <div style={{
                  marginTop: 8,
                  padding: 8,
                  background: '#f5f5f5',
                  borderRadius: 4,
                  fontSize: 12,
                  maxHeight: 100,
                  overflow: 'auto'
                }}>
                  {ocrResult.full_text}
                </div>
              </Card>
            )}
          </div>
        )}

        {/* 处理失败的情况 */}
        {uploadedFile && !isProcessing && !ocrResult && (
          <Alert
            message="OCR 识别失败"
            description="无法识别图片内容，请检查图片质量或重新上传"
            type="warning"
            showIcon
            style={{ marginTop: 16 }}
          />
        )}
      </Card>

      {/* 图片预览 Modal */}
      {previewVisible && uploadedFile && (
        <div
          style={{
            position: 'fixed',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            background: 'rgba(0,0,0,0.8)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            zIndex: 1000,
            cursor: 'pointer'
          }}
          onClick={() => setPreviewVisible(false)}
        >
          <img
            src={URL.createObjectURL(uploadedFile)}
            alt="预览"
            style={{
              maxWidth: '90%',
              maxHeight: '90%',
              objectFit: 'contain'
            }}
          />
        </div>
      )}
    </div>
  )
}

export default ImageUploader
